<?php

namespace app\admin\model\order;

use app\model\Order;
use app\model\TakeoutOrder;
use think\facade\Db;
use think\facade\Log;
use app\common\model\Export;

class Takeout
{
    private $table = 'takeout_order';
    private $error = '';

    /**
     * 列表.
     */
    public function getList($params)
    {
        $where = [];
        $agentName = $params['agent_name'] ?? '';
        if ($agentName) {
            $agentId = Db::name('agent')
                ->where('username|company_name', 'like', '%'.$agentName.'%')
                ->column('id');
            if ($agentId) {
                $where[] = ['agent_id', 'in', $agentId];
            } else {
                $where[] = ['agent_id', '=', -1];
            }
        }
        $orderId = trim($params['order_id'] ?? '');
        if ($orderId) {
            $where[] = ['order_id', '=', $orderId];
        }
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }
        if (!empty($params['order_type'])) {
            $where[] = ['order_type', '=', $params['order_type']];
        }
        if (!empty($params['ordertime'])) {
            $where[] = ['ordertime', '>=', strtotime($params['ordertime'][0])];
            $where[] = ['ordertime', '<=', strtotime($params['ordertime'][1] . ' 23:59:59')];
        }

        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        if (!empty($params['is_export'])) {
            // 返回导出 excel 需要的数据
            $list = TakeoutOrder::query()
                ->withSearch(['app_id','merchant_id'],request()->all())
                ->with((new Order())->getWith())
                ->where($where)
                ->order('id desc')
                ->select()
                ->toArray();
            $agentIds = array_column($list, 'agent_id');
        } else {
            $list = TakeoutOrder::query()
                ->withSearch(['app_id','merchant_id'],request()->all())
                ->with((new Order())->getWith())
                ->where($where)
                ->order('id desc')
                ->paginate($paginate)
                ->toArray();
            $agentIds = array_column($list['data'], 'agent_id');
        }
        if ($agentIds) {
            $agent = Db::name('agent')
                ->whereIn('id', $agentIds)
                ->column('username, company_name', 'id');
        }

        // 导出数据字段处理
        if (!empty($params['is_export'])) {
            $res = [];
            $title = ['订单号', '所属平台', '产品名称', '订单金额', '预估佣金', '状态', '下单时间', '代理商用户名', '代理商公司名称'];
            $orderTypeMap = [
                1 => '美团',
                2 => '饿了么',
                3 => '美团到店',
            ];
            $statusMap = [
                8 => '已完成',
                9 => '已取消',
            ];
            foreach ($list as $v) {
                if ($v['ordertime']) {
                    $v['ordertime'] = date('Y-m-d H:i:s', $v['ordertime']);
                } else {
                    $v['ordertime'] = '';
                }
                $res[] = [
                    $v['order_id']."\t",
                    $orderTypeMap[$v['order_type']],
                    $v['title'],
                    fen2yuan($v['payprice']).'',
                    fen2yuan($v['profit']).'',
                    $statusMap[$v['status']] ?? '已支付',
                    $v['ordertime'],
                    $agent[$v['agent_id']]['username'] ?? '',
                    $agent[$v['agent_id']]['company_name'] ?? '',
                ];
            }
            unset($list);
            $export = new Export;
            $name = '外卖订单';
            return $export->downloadExcel($title, $res, $name);
        }

        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['agent_name'] = $agent[$v['agent_id']]['username'] ?? '';
            $list['data'][$k]['company_name'] = $agent[$v['agent_id']]['company_name'] ?? '';
            $list['data'][$k]['order_id'] = strval($v['order_id']);
            if ($v['ordertime']) {
                $list['data'][$k]['ordertime'] = date('Y-m-d H:i:s', $v['ordertime']);
            } else {
                $list['data'][$k]['ordertime'] = '';
            }
        }

        return success('操作成功', $list);
    }

    public function getError()
    {
        return $this->error;
    }
}
